<template>
  <div :title="getTile()"
       class="element-library-preview-item"
       @contextmenu="contextEventHandler"
       @dblclick="dblclickEventHandler"
       @mousedown="mousedownEventHandler"
       @click="clickEventHandler"
       :class="{'active':selected | isInserting }">
    <img v-if="isFolder" src="./images/file.svg" class="folder-img">
    <img v-else :src="item.thumbnail" draggable="false" class="preview-img">
    <p v-if="!rename" class="item-name">{{ item.name }}</p>
    <el-tooltip v-else
                v-model="error"
                :content="$t(errorTipContent)"
                placement="bottom"
                effect="light"
                :manual="true">
      <input ref="renameInput"
             @input="nameInputEventHandler"
             @blur.stop="inputBlurEventHandler"
             @keydown.enter.stop="inputBlurEventHandler"
             class="preview-rename-input"
             :value.trim="item.name"
             v-focus/>
    </el-tooltip>

  </div>
</template>

<script>

  import {LibraryItem, LibraryModelType, LibraryType} from "./js/ElementLibraryTypes";
  import elementLibraryManager from "./js/ElementLibraryManager";
  import {eventBus} from "../../../eventbus/eventbus";
  import {elementLibraryCmd} from "../../../Command/ElementLibrary/ElementLibraryCommand";

  export default {
    name: "ElementLibraryPreviewItem",
    inject: ["rightClickItem", "selectItemHandler", "openFolderEventHandler"],
    props: {
      item: LibraryItem,
      selected: Boolean,
      openFolder: Object,
    },
    data() {
      return {
        // 是否处于拖拽
        isDrag: false,
        rename: false,
        enterPress: false,
        oldName: "",
        error: false,
        errorTipContent: "message.ElementLibrary.fileNameErrorTip",
      }
    },
    mounted() {
      this.renameId = eventBus.on("renameElementLibraryItemPreview", (id) => {
        if (id === this.item.id) {
          this.rename = true;
          this.enterPress = false;
          this.oldName = this.item.name;
          this.$nextTick(() => {
            this.$refs.renameInput.focus();
          });
        }
      })
    },
    methods: {
      nameInputEventHandler(e) {
        // if (!specialSymbol.test(e.data)) {
          this.item.name = e.target.value;
        // } else {
        //   this.error = true;
        //   e.target.value = this.item.name;
        //   this.errorTipContent = this.$t('message.ElementLibrary.fileNameErrorTip');
        // }
      },
      inputBlurEventHandler() {
        if (this.enterPress || this.error) return;
        this.item.name = this.item.name.trim();
        if (!this.item.name) {
          this.error = true;
          this.errorTipContent = this.$t('message.DocumentList.unnamedValid');
          return;
        }
        // else if(NameChecker.checkLimitStr(this.item.name)) {
        //   this.error = true;
        //   this.errorTipContent = this.$t('message.ProjectList.nameExceedLength');
        //   return;
        // }
        this.rename = false;
        this.enterPress = true;
        // 如果是重命名状态
        // 名字没有发生面板
        if (this.oldName === this.item.name) return;
        let params = {
          cmdName: 'renameElementLibraryItem',
          id: this.item.id,
          folderCode: this.item.folderCode,
          name: this.item.name,
        }
        elementLibraryCmd.executeElementLibraryCommand(params, res => {
          if (res.status === 200 && res.data.code === 200) {
            eventBus.emit("alert", "重命名成功", {type: "success"});
            this.clickEventHandler();
            elementLibraryManager.renameItem(this.item.id, this.item.name);
          } else {
            // 存在同名文件
            // 该变量用于标识用户是否执行过模态框的交互按钮
            // TODO: 由于模态框存在BUG，现在需要用它标识，后期如果BUG修复可以将该变量移除
            eventBus.emit("confirm", "警告", "当前目录下存在同名文件或文件夹，之后的文件将在名称中添加一个编号", {
              type: "warning",
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              confirmCallback: () => {
                let childrenList = elementLibraryManager.getParentByItem(this.item)?.children ?? elementLibraryManager.elementLibraryItems;
                let newName = elementLibraryManager.generateNameByNo(this.item.name, childrenList.filter(child => child.id !== this.item.id).map(child => child.name));
                if (this.oldName !== newName) {
                  let parameters = {
                    cmdName: 'renameElementLibraryItem',
                    id: this.item.id,
                    folderCode: this.item.folderCode,
                    name: newName,
                  }
                  elementLibraryCmd.executeElementLibraryCommand(parameters, res => {
                    if (res.status === 200 && res.data.code === 200) {
                      elementLibraryManager.renameItem(this.item.id, newName);
                      eventBus.emit("alert", "重命名成功", {type: "success"});
                    }
                  });
                }
                this.item.name = this.oldName;
                this.oldName = "";
              },
              closeCallback: () => {
                this.item.name = this.oldName;
                this.oldName = "";
              }
            })
          }
        });
      },
      mousedownEventHandler(e) {
        window.addEventListener("mousemove", this.mousemoveEventHandler);
        window.addEventListener("mouseup", this.mouseupEventHandler);
      },
      mousemoveEventHandler(e) {
        let inWorkArea = e.target.closest("#workAreaCanvas");
        // 当前是否在工作工作空间内
        if (this.isDrag) return;
        if (inWorkArea) {
          elementLibraryManager.insert(this.item, true);
          this.isDrag = true;
        }
      },
      mouseupEventHandler(e) {
        window.removeEventListener("mousemove", this.mousemoveEventHandler);
        this.isDrag = false;
      },
      dblclickEventHandler() {
        if (this.item.libraryType !== LibraryType.FOLDER) return;
        this.openFolderEventHandler(this.item.id);
        eventBus.emit("openElementLibraryFolder", this.item.id);
      },
      getTile() {
        let title = "";

        title += `文件名称: ${this.item.name}`;
        //类型
        switch (this.item.libraryType) {
          case LibraryType.FOLDER:
            title += this.$t('message.ElementLibrary.folder');
            break;
          case LibraryType.MODEL:
            title += this.$t('message.ElementLibrary.model');
            break;
        }

        // 模型独有的
        if (this.item.libraryType === LibraryType.MODEL) {
          title += this.item.param.modelType === LibraryModelType.Part ? this.$t('message.ElementLibrary.part') : this.$t('message.ElementLibrary.assembly');
          title += this.item.param.isParametric ? this.$t('message.ElementLibrary.yes') : this.$t('message.ElementLibrary.no');
        }

        title += this.item.system ? this.$t('message.ElementLibrary.system') : this.$t('message.ElementLibrary.custom');

        return title;
      },
      contextEventHandler(e) {
        this.clickEventHandler();
        this.rightClickItem(e, true);
      },
      clickEventHandler() {
        let targetItem = this.item;
        elementLibraryManager.openAllParentFolder(targetItem, "library");
        this.selectItemHandler(this.item);
      }
    },
    computed: {
      isFolder() {
        return this.item.libraryType === LibraryType.FOLDER;
      },
      isInserting() {
        return elementLibraryManager.curInsertItem?.id === this.item.id;
      }
    },
    beforeDestroy() {
      eventBus.off("renameElementLibraryItemPreview", this.renameId);
    },
    watch: {
      error: {
        handler(val) {
          if (val === false) return;
          if (this.errorTimer) {
            clearTimeout(this.errorTimer);
          }
          this.errorTimer = setTimeout(() => {
            this.error = false;
          }, 1000)
        }
      },
    }
  }
</script>

<style scoped>
  .element-library-preview-item {
    margin-left: 0.375rem;
    margin-right: 0.375rem;
    margin-top: 0.25rem;
    margin-bottom: 0.25rem;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    width: 96px;
    cursor: pointer;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    flex-direction: column;
    -webkit-box-align: center;
    -webkit-align-items: center;
    align-items: center;
    border-radius: 0.25rem;
    padding-top: 0.25rem;
    padding-bottom: 0.25rem;
    padding-left: 0.5rem;
    padding-right: 0.5rem;
  }

  .active {
    background-color: var(--bg-color8);
  }

  .preview-img {
    height: 64px;
    width: 100%;
    --tw-bg-opacity: 1;
    background-color: rgb(255 255 255 / var(--tw-bg-opacity));
  }

  .folder-img {
    height: 64px;
    width: 100%;
    padding: 0.25rem;
  }

  .item-name {
    max-width: 80px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .item-path {
    color: var(--text-color3);
    @apply tw-text-sm;
  }

  .preview-rename-input {
    width: 60px;
  }
</style>